package org.vdab.projects.tasks.client.entities;

import java.util.HashSet;
import java.util.Set;

import org.vdab.projects.tasks.client.dal.GWTEntityManager;
import org.vdab.projects.tasks.client.util.DelayedList;
import org.vdab.projects.tasks.client.util.ICommand;
import org.vdab.projects.tasks.client.util.MessageGuard;
import org.vdab.projects.tasks.shared.entities.IBaseEntity;
import org.vdab.projects.tasks.shared.entities.ITaskBook;
import org.vdab.projects.tasks.shared.entities.ITaskList;
import org.vdab.projects.tasks.shared.entities.impl.TaskBook;
import org.vdab.projects.tasks.shared.entities.impl.TaskList;

import com.google.gwt.user.client.rpc.AsyncCallback;

public class ClientTaskBook extends ClientEntity<TaskBook> implements ITaskBook{


	public ClientTaskBook(TaskBook sso,GWTEntityManager em) {		
		super(sso,em);		
	}

	@Override
	protected void load(String key, AsyncCallback<TaskBook> asyncCallback) {
		//TODO: Implement
		//As for now, a ClientTaskBook will only be created when the ServerTaskBook is available.
		//There is no need to load a TaskBook based on it key
		MessageGuard.Log("Tried to load a taskbook by it's key ("+ key +"). This should not occure." );
	}

	public ClientTaskList createNewTaskList() throws Exception {
		final TaskList tl = new TaskList("New TaskList").init();
		ClientTaskList newTaskList = new ClientTaskList(tl,this.getManager());
		this.addTaskList(newTaskList);
		return newTaskList;
	}

	@Override
	public IBaseEntity<TaskBook> save() throws Exception {
		if(super.isLoaded()){
			super.execute(new ICommand<TaskBook>() {				
				@Override
				public void execute(TaskBook entity) throws Exception {					
					entity.save();
				}
			});
		}
		return this;
	}

	@Override
	public void addTaskList(final ITaskList taskList) throws Exception {
		this.execute( new ICommand<TaskBook>() {
			@Override
			public void execute(final TaskBook tb) throws Exception {
				taskList.execute(new ICommand<TaskList>() {					
					@Override
					public void execute(TaskList tl) throws Exception {
						tb.addTaskList(tl);
						tb.save();			}
				});				
			}
		});
	}

	@Override
	public Set<ITaskList> getTaskLists() throws Exception {
		return new HashSet<ITaskList>(getClientTaskLists(new DelayedList<ClientTaskList>()));
	}

	public DelayedList<ClientTaskList> getClientTaskLists(final DelayedList<ClientTaskList> list) throws Exception {
		//final DelayedList<ITaskList> list = new DelayedList<ITaskList>();
		
		
		this.execute(new ICommand<TaskBook>() {
			@Override
			public void execute(TaskBook entity) throws Exception {
				for(ITaskList tl : entity.getTaskLists()){
					tl.execute(new ICommand<TaskList>() {						
						@Override
						public void execute(TaskList entity) throws Exception {
							list.addEntity(new ClientTaskList(entity,getManager()));
						}
					});					
				}
			}
		});		
		return list;
	}


	
}


